package com.zhihuichongcheng.application.ui.im.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.bumptech.glide.Glide;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.smartlib.cmnObject.recycleView.OnItemLongClick;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.smartlib.cmnObject.util.DateUtil;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.SPUtil;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.glide.GlideCircleTransform;
import com.zhihuichongcheng.application.ui.BaseApplication;
import com.zhihuichongcheng.application.widget.EaseConversationList;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * conversation list adapter
 */
public class EaseConversationAdapter extends RecyclerView.Adapter<EaseConversationAdapter.ViewHolder> {
    private static final String TAG = "ChatAllHistoryAdapter";
    protected int primaryColor;
    protected int secondaryColor;
    protected int timeColor;
    protected int primarySize;
    protected int secondarySize;
    protected float timeSize;
    private List<EMConversation> conversationList;
    private List<EMConversation> copyConversationList;
    //    private ConversationFilter conversationFilter;
    private boolean notiyfyByFilter;
    private OnItemOnclick<EMConversation> onItemOnclick;
    private OnItemLongClick<EMConversation> mOnItemLongClick;
    private Context mContext;
    private BaseApplication app;
    private List<UserBean> mFriends = new ArrayList<>();
    private EaseConversationList.EaseConversationListHelper cvsListHelper;

    public EaseConversationAdapter(Context context, int resource,
                                   List<EMConversation> objects) {
        this.mContext = context;
        app = (BaseApplication) context.getApplicationContext();
        UserBean bean = app.getUser();
        if (bean != null) {
            mFriends = bean.getFriends();
        }

        conversationList = objects;
        copyConversationList = new ArrayList<>();
        copyConversationList.addAll(objects);
    }

    public void setOnItemOnclick(OnItemOnclick<EMConversation> onItemOnclick) {
        this.onItemOnclick = onItemOnclick;
    }

    public void setOnItemLongClick(OnItemLongClick<EMConversation> onItemLongClick) {
        mOnItemLongClick = onItemLongClick;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.ease_row_chat_history, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final EMConversation conversation = conversationList.get(position);
        String username = conversation.getUserName();
        if (conversation.getType() == EMConversationType.GroupChat) {
            String groupId = conversation.getUserName();
            if (EaseAtMessageHelper.get().hasAtMeMsg(groupId)) {
                holder.motioned.setVisibility(View.VISIBLE);
            } else {
                holder.motioned.setVisibility(View.GONE);
            }
            Glide.with(mContext).load(R.drawable.ic_chat_group_defalut).transform(new GlideCircleTransform(mContext)).into(holder.avatar);
            EMGroup group = EMClient.getInstance().groupManager().getGroup(username);

            holder.name.setText(group != null ? group.getGroupName() : username);
        } else if (conversation.getType() == EMConversationType.ChatRoom) {
            holder.avatar.setImageResource(R.drawable.ic_chat_group_defalut);
            EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
            holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
            holder.motioned.setVisibility(View.GONE);
        } else {
            UserBean bean = check(username);
            if (bean != null) {
                Glide.with(mContext).load(bean.getLogoUrl()).transform(new GlideCircleTransform(mContext)).placeholder(R.drawable.ic_default_avatar).into(holder.avatar);
                holder.name.setText(bean.getUserName());
            } else {
                Glide.with(mContext).load("").transform(new GlideCircleTransform(mContext)).placeholder(R.drawable.ic_default_avatar).into(holder.avatar);
                holder.name.setText("");
            }
            holder.motioned.setVisibility(View.GONE);
        }

        if (conversation.getUnreadMsgCount() > 0) {
            // show unread message count
            holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
            holder.unreadLabel.setVisibility(View.VISIBLE);
        } else {
            holder.unreadLabel.setVisibility(View.GONE);
        }
        if (conversation.getAllMsgCount() != 0) {
            EMMessage lastMessage = conversation.getLastMessage();
            String content = null;
            if (cvsListHelper != null) {
                content = cvsListHelper.onSetItemSecondaryText(lastMessage);
            }
            holder.message.setText(EaseSmileUtils.getSmiledText(mContext, EaseCommonUtils.getMessageDigest(lastMessage, (this.mContext))),
                    BufferType.SPANNABLE);
            if (content != null) {
                holder.message.setText(content);
            }
            holder.time.setText(DateUtil.format(new Date(lastMessage.getMsgTime())));
            if (lastMessage.direct() == EMMessage.Direct.SEND && lastMessage.status() == EMMessage.Status.FAIL) {
                holder.msgState.setVisibility(View.VISIBLE);
            } else {
                holder.msgState.setVisibility(View.GONE);
            }
        }
        if (position == conversationList.size() - 1) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.mViewBottom.getLayoutParams();
            params.setMargins(0, 0, 0, 0);
            holder.mViewBottom.setLayoutParams(params);
            holder.mViewBottom.setVisibility(View.VISIBLE);
        } else {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.mViewBottom.getLayoutParams();
            params.setMargins(DeviceUtil.dip2px(mContext, 66), 0, 0, 0);
            holder.mViewBottom.setLayoutParams(params);
            holder.mViewBottom.setVisibility(View.VISIBLE);
        }
        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemOnclick != null) {
                    onItemOnclick.onClick(conversation, position);
                }
            }
        });
        holder.view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnItemLongClick != null) {
                    return mOnItemLongClick.onClick(conversation, position);
                }
                return false;
            }
        });
    }

    private UserBean check(String user) {
        SPUtil spUtil = SPUtil.getInstance(mContext);
        UserBean userBean = spUtil.getObject(user, UserBean.class);
        return userBean;
    }

    @Override
    public int getItemCount() {
        return conversationList.size();
    }

    public void setPrimaryColor(int primaryColor) {
        this.primaryColor = primaryColor;
    }

    public void setSecondaryColor(int secondaryColor) {
        this.secondaryColor = secondaryColor;
    }

    public void setTimeColor(int timeColor) {
        this.timeColor = timeColor;
    }

    public void setPrimarySize(int primarySize) {
        this.primarySize = primarySize;
    }


//    private class ConversationFilter extends Filter {
//        List<EMConversation> mOriginalValues = null;
//
//        public ConversationFilter(List<EMConversation> mList) {
//            mOriginalValues = mList;
//        }
//
//        @Override
//        protected FilterResults performFiltering(CharSequence prefix) {
//            FilterResults results = new FilterResults();
//
//            if (mOriginalValues == null) {
//                mOriginalValues = new ArrayList<EMConversation>();
//            }
//            if (prefix == null || prefix.length() == 0) {
//                results.values = copyConversationList;
//                results.count = copyConversationList.size();
//            } else {
//                String prefixString = prefix.toString();
//                final int count = mOriginalValues.size();
//                final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>();
//
//                for (int i = 0; i < count; i++) {
//                    final EMConversation value = mOriginalValues.get(i);
//                    String username = value.getUserName();
//
//                    EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
//                    if(group != null){
//                        username = group.getGroupName();
//                    }else{
//                        EaseUser user = EaseUserUtils.getUserInfo(username);
////                        if(user != null && user.getNick() != null)
////                            username = user.getNick();
////                        SPUtil spUtil = SPUtil.getInstance(mContext);
////                        UserBean bean = spUtil.getObject(username,UserBean.class);
////                        username = bean.getUserName();
//                    }
//
//                    // First match against the whole ,non-splitted value
//                    if (username.startsWith(prefixString)) {
//                        newValues.add(value);
//                    } else{
//                          final String[] words = username.split(" ");
//                            final int wordCount = words.length;
//                            // Start at index 0, in case valueText starts with space(s)
//                        for (String word : words) {
//                            if (word.startsWith(prefixString)) {
//                                newValues.add(value);
//                                break;
//                            }
//                        }
//                    }
//                }
//
//                results.values = newValues;
//                results.count = newValues.size();
//            }
//            return results;
//        }
//
//        @Override
//        protected void publishResults(CharSequence constraint, FilterResults results) {
//            conversationList.clear();
//            if (results.values != null) {
//                conversationList.addAll((List<EMConversation>) results.values);
//            }
//            if (results.count > 0) {
//                notiyfyByFilter = true;
//                notifyDataSetChanged();
//            } else {
//                notifyDataSetInvalidated();
//            }
//        }
//    }

    public void setSecondarySize(int secondarySize) {
        this.secondarySize = secondarySize;
    }

    public void setTimeSize(float timeSize) {
        this.timeSize = timeSize;
    }

    public void setCvsListHelper(EaseConversationList.EaseConversationListHelper cvsListHelper) {
        this.cvsListHelper = cvsListHelper;
    }

    public void setData(List<EMConversation> objects) {
        conversationList = objects;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        /**
         * who you chat with
         */
        TextView name;
        /**
         * unread message count
         */
        TextView unreadLabel;
        /**
         * content of last message
         */
        TextView message;
        /**
         * time of last message
         */
        TextView time;
        /**
         * avatar
         */
        ImageView avatar;
        /**
         * status of last message
         */
        View msgState, view, mViewBottom;
        /**
         * layout
         */
        RelativeLayout list_itease_layout;
        TextView motioned;


        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            name = (TextView) itemView.findViewById(R.id.name);
            unreadLabel = (TextView) itemView.findViewById(R.id.unread_msg_number);
            message = (TextView) itemView.findViewById(R.id.message);
            time = (TextView) itemView.findViewById(R.id.time);
            avatar = (ImageView) itemView.findViewById(R.id.avatar);
            msgState = itemView.findViewById(R.id.msg_state);
            list_itease_layout = (RelativeLayout) itemView.findViewById(R.id.list_itease_layout);
            motioned = (TextView) itemView.findViewById(R.id.mentioned);
            mViewBottom = (View) itemView.findViewById(R.id.view_bottom);
        }
    }
}

